// 页面渲染API客户端
class PageAPI {
    constructor() {
        this.baseURL = '/api';
    }

    // 获取版本信息 - 对应 GET /api/version
    async getVersionInfo() {
        try {
            const response = await fetch(`${this.baseURL}/version`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('获取版本信息失败:', error);
            throw error;
        }
    }

    // 页面初始化
    async initializePage() {
        try {
            // 获取版本信息并更新页面
            const versionInfo = await this.getVersionInfo();
            this.updateVersionDisplay(versionInfo);
            
            // 初始化页面元素
            this.initializeElements();
            
            return true;
        } catch (error) {
            console.error('页面初始化失败:', error);
            return false;
        }
    }

    // 更新版本显示
    updateVersionDisplay(versionInfo) {
        const elements = {
            'app-version': versionInfo.version,
            'app-name': versionInfo.app_name,
            'app-description': versionInfo.description
        };

        Object.keys(elements).forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = elements[id];
            }
        });
    }

    // 初始化页面元素
    initializeElements() {
        // 设置当前时间
        this.updateCurrentTime();
        setInterval(() => this.updateCurrentTime(), 1000);

        // 初始化工具提示
        this.initializeTooltips();

        // 初始化响应式布局
        this.initializeResponsiveLayout();

        // 初始化主题切换
        this.initializeThemeSwitch();
    }

    // 更新当前时间
    updateCurrentTime() {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });

        const timeElements = document.querySelectorAll('.current-time');
        timeElements.forEach(el => {
            el.textContent = timeString;
        });
    }

    // 初始化工具提示
    initializeTooltips() {
        const tooltipElements = document.querySelectorAll('[data-tooltip]');
        tooltipElements.forEach(element => {
            element.addEventListener('mouseenter', (e) => {
                this.showTooltip(e.target, e.target.getAttribute('data-tooltip'));
            });

            element.addEventListener('mouseleave', () => {
                this.hideTooltip();
            });
        });
    }

    // 显示工具提示
    showTooltip(element, text) {
        const tooltip = document.createElement('div');
        tooltip.className = 'tooltip';
        tooltip.textContent = text;
        
        document.body.appendChild(tooltip);

        const rect = element.getBoundingClientRect();
        tooltip.style.left = `${rect.left + rect.width / 2}px`;
        tooltip.style.top = `${rect.top - tooltip.offsetHeight - 5}px`;
        tooltip.style.transform = 'translateX(-50%)';
    }

    // 隐藏工具提示
    hideTooltip() {
        const tooltip = document.querySelector('.tooltip');
        if (tooltip) {
            tooltip.remove();
        }
    }

    // 初始化响应式布局
    initializeResponsiveLayout() {
        const handleResize = () => {
            const width = window.innerWidth;
            const body = document.body;

            // 移除现有的响应式类
            body.classList.remove('mobile', 'tablet', 'desktop');

            // 添加对应的响应式类
            if (width < 768) {
                body.classList.add('mobile');
            } else if (width < 1024) {
                body.classList.add('tablet');
            } else {
                body.classList.add('desktop');
            }
        };

        // 初始调用
        handleResize();

        // 监听窗口大小变化
        window.addEventListener('resize', handleResize);
    }

    // 初始化主题切换
    initializeThemeSwitch() {
        // 从localStorage获取保存的主题
        const savedTheme = localStorage.getItem('theme') || 'light';
        this.setTheme(savedTheme);

        // 主题切换按钮
        const themeToggle = document.getElementById('theme-toggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', () => {
                const currentTheme = document.body.getAttribute('data-theme') || 'light';
                const newTheme = currentTheme === 'light' ? 'dark' : 'light';
                this.setTheme(newTheme);
            });
        }
    }

    // 设置主题
    setTheme(theme) {
        document.body.setAttribute('data-theme', theme);
        localStorage.setItem('theme', theme);

        // 更新主题切换按钮文本
        const themeToggle = document.getElementById('theme-toggle');
        if (themeToggle) {
            themeToggle.textContent = theme === 'light' ? '🌙' : '☀️';
        }
    }

    // 显示加载状态
    showLoading(container, message = '加载中...') {
        if (typeof container === 'string') {
            container = document.getElementById(container);
        }
        
        if (container) {
            container.innerHTML = `
                <div class="loading-container">
                    <div class="loading-spinner"></div>
                    <div class="loading-text">${message}</div>
                </div>
            `;
        }
    }

    // 隐藏加载状态
    hideLoading(container) {
        if (typeof container === 'string') {
            container = document.getElementById(container);
        }
        
        if (container) {
            const loadingContainer = container.querySelector('.loading-container');
            if (loadingContainer) {
                loadingContainer.remove();
            }
        }
    }

    // 显示错误信息
    showError(container, message, isRetryable = false) {
        if (typeof container === 'string') {
            container = document.getElementById(container);
        }
        
        if (container) {
            const retryButton = isRetryable ? 
                '<button class="retry-btn" onclick="location.reload()">重试</button>' : '';
            
            container.innerHTML = `
                <div class="error-container">
                    <div class="error-icon">⚠️</div>
                    <div class="error-message">${message}</div>
                    ${retryButton}
                </div>
            `;
        }
    }

    // 安全的HTML转义
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 格式化数字
    formatNumber(number, decimals = 2) {
        return parseFloat(number).toFixed(decimals);
    }

    // 动画效果
    animateElement(element, animation = 'fadeIn', duration = 300) {
        if (typeof element === 'string') {
            element = document.getElementById(element);
        }
        
        if (element) {
            element.style.animation = `${animation} ${duration}ms ease-in-out`;
            
            setTimeout(() => {
                element.style.animation = '';
            }, duration);
        }
    }

    // 错误处理
    handleError(error, context = '页面API') {
        console.error(`${context}错误:`, error);
        
        if (error.name === 'TypeError' && error.message.includes('fetch')) {
            return '网络连接失败，请检查服务器状态';
        } else if (error.message.includes('404')) {
            return '页面资源未找到';
        } else if (error.message.includes('500')) {
            return '服务器内部错误';
        } else {
            return error.message || '未知错误';
        }
    }
}

// 创建全局实例
window.pageAPI = new PageAPI();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.pageAPI.initializePage();
});